package com.cheng.controller;


import com.baomidou.mybatisplus.mapper.Condition;
import com.cheng.entity.MsgResponse;
import com.cheng.entity.Users;
import com.cheng.service.TiebaService;
import com.cheng.service.UsersService;
import com.cheng.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Cheng
 * @since 2019-07-31
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private TiebaService tiebaService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private EmailUtil emailUtil;

    @PostMapping("/addEmail")
    public MsgResponse addEmail(@RequestBody Users userOne) {
        MsgResponse msgResponse = new MsgResponse();
        String qq = userOne.getQq();
        String email = userOne.getEmail();
        if (!qq.matches("[0-9]{5,}") || !email.matches("[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+")) {
            return msgResponse.setCode(1001).setMsg("QQ或邮箱格式不对，QQ应为五位以上纯数字，邮箱为标准邮箱格式，不允许特殊符号");
        }
        List list = tiebaService.selectList(Condition.create().eq("qq", qq));
        if (list == null || list.size() < 1) {
            return msgResponse.setCode(1001).setMsg("验证失败,未找到该QQ用户");
        }
//        获取上次激活/添加时间
        Long mins = (Long) usersService.selectObj(Condition.create().setSqlSelect("TIMESTAMPDIFF(MINUTE, activ_time,now())").eq("qq", qq));
        if (mins != null && mins <= 1440) {
            return msgResponse.setCode(1001).setMsg("添加或更新24小时后才能再次操作");
        }
        Users users = new Users();
        String verifCode = UUID.randomUUID().toString().replace("-", "");
        users.setQq(qq).setEmail(email)
                .setEmailStatus(0)
                .setActivTime(new Date())
                .setVerifCode(verifCode);
        try {
            users.insert();
        } catch (Exception e) {
            users.updateById();
        }
        try {
            emailUtil.simpleSend(email, "贴吧助手邮箱激活", "请点击或将此链接复制到浏览器访问即可：http://hik.win/users/verEmail?vercode=" + verifCode);
        } catch (Exception e) {
            e.printStackTrace();
            return msgResponse.setCode(1001).setMsg("发送激活邮件失败!请联系管理员或重新绑定");
        }
        return msgResponse.setCode(1000).setMsg("添加/修改邮箱成功,请至自己邮箱访问验证链接");
    }

    @GetMapping("/verEmail")
    public MsgResponse verEmail(String vercode) {
        MsgResponse msg = new MsgResponse();
        List<Users> users = usersService.selectList(Condition.create().eq("verif_code", vercode).last("limit 1"));
        if (users == null || users.size() <= 0) {
            return msg.setCode(1002).setMsg("无效验证链接");
        }
        Users user = users.get(0);
        if (user.getEmailStatus() == 1) {
            return msg.setCode(1002).setMsg("已激活 无需重复激活");
        }
        Long mins = (Long) usersService.selectObj(Condition.create().setSqlSelect("TIMESTAMPDIFF(MINUTE, activ_time,now())").eq("verif_code", vercode));
        if (mins > 1440) {
            return msg.setCode(1001).setMsg("激活码失效(超过24h) 请重新绑定邮箱");
        }
        user.setActivTime(new Date()).setEmailStatus(1).updateById();
        return msg.setCode(1000).setMsg("激活成功");
    }

    @GetMapping("/searchEmail")
    public MsgResponse searchEmail(String qq) {
        MsgResponse msg = new MsgResponse();
        Users user = new Users().selectById(qq);
        if (user == null) {
            return msg.setCode(1001).setMsg("未找到该QQ,请核对");
        }
        user.setEmail(emailUtil.encodeEmail(user.getEmail())).setVerifCode(null);
        return msg.setCode(1000).setMsg(user);
    }

}
